import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { 
  BUSINESS_ERROR_CODES, 
  COMMON_ERROR_CODES
} from '../../utils/errorCodes';

export class NotificationController extends BaseController {
  // 获取用户通知列表
  async getNotifications(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = (req as any).user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, COMMON_ERROR_CODES.UNAUTHORIZED, '用户未登录');
        return;
      }

      const { page = 1, limit = 20, type } = req.query;
      const skip = (Number(page) - 1) * Number(limit);

      // 构建查询条件
      const where: any = { userId };
      if (type) {
        where.type = type;
      }

      // 获取通知列表
      const [notifications, total] = await Promise.all([
        prisma.notification.findMany({
          where,
          orderBy: { createdAt: 'desc' },
          skip,
          take: Number(limit),
          include: {
            user: {
              select: {
                id: true,
                username: true,
                realName: true,
                avatar: true
              }
            }
          }
        }),
        prisma.notification.count({ where })
      ]);

      // 获取未读数量
      const unreadCount = await prisma.notification.count({
        where: {
          userId,
          isRead: false
        }
      });

      ResponseUtils.success(res, {
        notifications,
        pagination: {
          page: Number(page),
          limit: Number(limit),
          total,
          totalPages: Math.ceil(total / Number(limit))
        },
        unreadCount
      }, '获取通知列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 标记通知为已读
  async markAsRead(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = (req as any).user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, COMMON_ERROR_CODES.UNAUTHORIZED, '用户未登录');
        return;
      }

      const { id } = req.params;

      // 检查通知是否存在且属于当前用户
      const notification = await prisma.notification.findFirst({
        where: {
          id: Number(id),
          userId
        }
      });

      if (!notification) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '通知不存在');
        return;
      }

      // 标记为已读
      await prisma.notification.update({
        where: { id: Number(id) },
        data: { isRead: true }
      });

      ResponseUtils.success(res, null, '标记已读成功');
    } catch (error) {
      next(error);
    }
  }

  // 标记所有通知为已读
  async markAllAsRead(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = (req as any).user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, COMMON_ERROR_CODES.UNAUTHORIZED, '用户未登录');
        return;
      }

      // 批量更新所有未读通知
      await prisma.notification.updateMany({
        where: {
          userId,
          isRead: false
        },
        data: { isRead: true }
      });

      ResponseUtils.success(res, null, '全部标记已读成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取用户通知设置
  async getNotificationSettings(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = (req as any).user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, COMMON_ERROR_CODES.UNAUTHORIZED, '用户未登录');
        return;
      }

      let settings = await prisma.userNotificationSettings.findUnique({
        where: { userId }
      });

      // 如果设置不存在，创建默认设置
      if (!settings) {
        settings = await prisma.userNotificationSettings.create({
          data: {
            userId,
            pushEnabled: true,
            emailEnabled: true,
            performanceReminder: true,
            voteReminder: true
          }
        });
      }

      ResponseUtils.success(res, settings, '获取通知设置成功');
    } catch (error) {
      next(error);
    }
  }

  // 更新用户通知设置
  async updateNotificationSettings(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = (req as any).user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, COMMON_ERROR_CODES.UNAUTHORIZED, '用户未登录');
        return;
      }

      const { 
        pushEnabled, 
        emailEnabled, 
        performanceReminder, 
        voteReminder 
      } = req.body;

      // 更新或创建通知设置
      const settings = await prisma.userNotificationSettings.upsert({
        where: { userId },
        update: {
          pushEnabled: pushEnabled !== undefined ? pushEnabled : undefined,
          emailEnabled: emailEnabled !== undefined ? emailEnabled : undefined,
          performanceReminder: performanceReminder !== undefined ? performanceReminder : undefined,
          voteReminder: voteReminder !== undefined ? voteReminder : undefined
        },
        create: {
          userId,
          pushEnabled: pushEnabled ?? true,
          emailEnabled: emailEnabled ?? true,
          performanceReminder: performanceReminder ?? true,
          voteReminder: voteReminder ?? true
        }
      });

      ResponseUtils.success(res, settings, '通知设置更新成功');
    } catch (error) {
      next(error);
    }
  }

  // 删除通知
  async deleteNotification(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = (req as any).user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, COMMON_ERROR_CODES.UNAUTHORIZED, '用户未登录');
        return;
      }

      const { id } = req.params;

      // 检查通知是否存在且属于当前用户
      const notification = await prisma.notification.findFirst({
        where: {
          id: Number(id),
          userId
        }
      });

      if (!notification) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '通知不存在');
        return;
      }

      // 删除通知
      await prisma.notification.delete({
        where: { id: Number(id) }
      });

      ResponseUtils.success(res, null, '删除通知成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取未读通知数量
  async getUnreadCount(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = (req as any).user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, COMMON_ERROR_CODES.UNAUTHORIZED, '用户未登录');
        return;
      }

      // 获取未读通知数量
      const count = await prisma.notification.count({
        where: {
          userId,
          isRead: false
        }
      });

      ResponseUtils.success(res, { count }, '获取未读通知数量成功');
    } catch (error) {
      next(error);
    }
  }
} 